<template>
  <div class="package-cost-selector" :class="{ 'selector-inline': inline }">
    <div class="selector-header" v-if="!inline">
      <h4 class="selector-title">包装方式</h4>
      <div class="search-box" v-if="packages.length > 0">
        <input 
          v-model="searchKeyword" 
          type="text" 
          placeholder="搜索包装方式..." 
          class="search-input"
        />
      </div>
    </div>

    <div class="loading-state" v-if="loading">
      <div class="spinner"></div>
      <span>加载包装列表中...</span>
    </div>

    <div class="error-state" v-if="errorMsg && !loading">
      <span class="error-text">{{ errorMsg }}</span>
    </div>

    <div class="packages-grid" v-if="!loading && filteredPackages.length > 0">
      <div v-for="pkg in filteredPackages" :key="pkg.id" class="package-item">
        <label class="package-radio">
          <input 
            type="radio" 
            :value="pkg.id" 
            :checked="selectedPackageId === pkg.id"
            class="radio-input"
            @click.prevent="handlePackageToggle(pkg)"
          />
          <div class="package-card" :class="{ 'is-selected': selectedPackageId === pkg.id }">
            <div class="card-top">
              <div class="card-main">
                <div class="card-header">
                  <span class="package-name">{{ pkg.name }}</span>
                  <span class="package-code">{{ pkg.code }}</span>
                </div>
                <div class="card-info">
                  <span class="unit-cost">¥ {{ (calcPackageCost(pkg) ?? 0).toFixed(2) }}</span>
                  <span v-if="pkg.unit" class="unit">/ {{ pkg.unit }}</span>
                </div>
              </div>
              <button 
                type="button" 
                class="view-bom-btn"
                @click.stop="$emit('view-bom', pkg)"
                title="查看该包装方式的BOM明细"
              >
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M4 4h9l7 7v9a0 0 0 0 1 0 0H4a0 0 0 0 1 0 0V4Z" />
                  <path d="M13 4v7h7" />
                </svg>
              </button>
            </div>
            <div v-if="pkg.description" class="card-desc">{{ pkg.description }}</div>
          </div>
        </label>
      </div>
    </div>

    <div class="empty-state" v-if="!loading && filteredPackages.length === 0 && packages.length === 0">
      <p>暂无可用的包装方式</p>
    </div>

    <div class="no-match-state" v-if="!loading && filteredPackages.length === 0 && packages.length > 0">
      <p>未找到匹配的包装方式</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { searchPackages, PackageItem } from '../../../services/package';

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  inline: {
    type: Boolean,
    default: false
  },
  packages: {
    type: Array,
    default: () => []
  },
  onCostChange: {
    type: Function,
    default: null
  }
});

const emit = defineEmits(['update:modelValue', 'cost-change', 'view-bom']);

// 如果 props 中传入了 packages，直接使用；否则初始化为空数组，稍后自动加载
const packages = ref<PackageItem[]>((props.packages && props.packages.length > 0) ? (props.packages as PackageItem[]) : []);
const loading = ref(!props.packages || (Array.isArray(props.packages) && props.packages.length === 0));
const errorMsg = ref('');
const searchKeyword = ref('');
const selectedPackageId = ref(props.modelValue);

// 监听 modelValue 的变化
watch(
  () => props.modelValue,
  newVal => {
    selectedPackageId.value = newVal;
  }
);

const filteredPackages = computed(() => {
  if (!searchKeyword.value.trim()) {
    return packages.value;
  }
  const keyword = searchKeyword.value.toLowerCase();
  return packages.value.filter(pkg =>
    pkg.name.toLowerCase().includes(keyword) ||
    (pkg.code && pkg.code.toLowerCase().includes(keyword)) ||
    (pkg.description && pkg.description.toLowerCase().includes(keyword))
  );
});

const selectedPackage = computed(() => {
  return packages.value.find(pkg => pkg.id === selectedPackageId.value);
});

async function loadPackages() {
  loading.value = true;
  errorMsg.value = '';
  try {
    const res = await searchPackages({ 
      page: 1, 
      pageSize: 100, 
      status: 'enabled' 
    });
    packages.value = res.data?.records || [];
  } catch (error: any) {
    errorMsg.value = error?.message || '加载包装列表失败';
    console.error('Failed to load packages:', error);
  } finally {
    loading.value = false;
  }
}

function handlePackageToggle(pkg: PackageItem) {
  // 支持切换选择：如果已选中则取消，否则选中
  if (selectedPackageId.value === pkg.id) {
    // 取消选择
    selectedPackageId.value = '';
    emit('update:modelValue', '');
    emit('cost-change', {
      packageId: '',
      packageName: '',
      packageCode: '',
      cost: 0
    });
  } else {
    // 选中包装
    selectedPackageId.value = pkg.id;
    const cost = calcPackageCost(pkg);
    emit('update:modelValue', pkg.id);
    emit('cost-change', {
      packageId: pkg.id,
      packageName: pkg.name,
      packageCode: pkg.code,
      cost: cost
    });
  }
}

function onPackageCardClick(pkg: PackageItem) {
  // 支持点击切换：如果点击的是已选中的，则取消；否则选中
  if (selectedPackageId.value === pkg.id) {
    // 取消选择
    selectedPackageId.value = '';
    emit('update:modelValue', '');
    emit('cost-change', {
      packageId: '',
      packageName: '',
      packageCode: '',
      cost: 0
    });
  } else {
    // 选中新的包装
    selectedPackageId.value = pkg.id;
    const cost = calcPackageCost(pkg);
    emit('update:modelValue', pkg.id);
    emit('cost-change', {
      packageId: pkg.id,
      packageName: pkg.name,
      packageCode: pkg.code,
      cost: cost
    });
  }
}

function handleCardClick(pkg: PackageItem) {
  // 只在卡片点击时处理取消选择
  // 如果用户点击了已选中的卡片，取消选择
  if (selectedPackageId.value === pkg.id) {
    selectedPackageId.value = '';
    emit('update:modelValue', '');
    emit('cost-change', {
      packageId: '',
      packageName: '',
      packageCode: '',
      cost: 0
    });
  }
}

// 计算包装成本（与 PackageMethodPage 中的 calcPackageCost 逻辑一致）
function calcPackageCost(pkg: PackageItem): number {
  // 首先尝试从 bomS 计算
  if (pkg.bomS && Array.isArray(pkg.bomS) && pkg.bomS.length > 0) {
    return pkg.bomS.reduce((sum: number, item: any) => {
      const bom = item.bom || {};
      const quantity = item.quantity || 1;
      const feeModel = bom.feeModel || 'fixed';
      const feeAmount = bom.feeAmount || 0;
      
      let lineCost = 0;
      if (feeModel === 'fixed') {
        lineCost = feeAmount;
      } else { // count
        lineCost = feeAmount * quantity;
      }
      return sum + lineCost;
    }, 0);
  }
  
  // fallback：如果没有 bomS，则使用 unitCost
  return pkg.unitCost ?? 0;
}

onMounted(() => {
  // 只在没有传入 packages 数据时才自动加载
  if (!props.packages || (Array.isArray(props.packages) && props.packages.length === 0)) {
    loadPackages();
  }
});

// 暴露获取当前选中包装的方法
function getSelectedPackage() {
  return selectedPackage.value || null;
}

function getCost() {
  if (!selectedPackage.value) return 0;
  return calcPackageCost(selectedPackage.value);
}

defineExpose({
  getSelectedPackage,
  getCost,
  selectedPackageId
});
</script>

<style scoped>
.package-cost-selector {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.package-cost-selector.selector-inline {
  flex-direction: row;
  gap: 0.6rem;
  flex-wrap: wrap;
  align-items: center;
  justify-content: flex-start;
}

.selector-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 0.6rem;
}

.package-cost-selector.selector-inline .selector-header {
  display: none;
}

.selector-title {
  margin: 0;
  font-size: 14px;
  font-weight: 700;
  letter-spacing: 0.05em;
  text-transform: uppercase;
  color: #475569;
  position: relative;
  padding-left: 10px;
}

.selector-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 60%;
  border-radius: 2px;
  background: linear-gradient(180deg, #10b981, #047857);
  box-shadow: 0 0 0 1px rgba(16, 185, 129, 0.15);
}

.search-box {
  display: flex;
  align-items: center;
}

.search-input {
  border: 1px solid #cbd5e1;
  border-radius: 10px;
  padding: 0.45rem 0.7rem;
  font-size: 13px;
  width: 220px;
  background: #fff;
  transition: border-color 0.18s, box-shadow 0.18s;
}

.search-input:focus {
  outline: 2px solid #3b82f6;
  outline-offset: 1px;
  border-color: #3b82f6;
}

.loading-state {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.8rem;
  padding: 1.5rem;
  color: #64748b;
  font-size: 14px;
}

.spinner {
  width: 20px;
  height: 20px;
  border: 2px solid #e2e8f0;
  border-top-color: #3b82f6;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.error-state {
  display: flex;
  align-items: center;
  padding: 0.8rem;
  background: #fee2e2;
  border: 1px solid #fecaca;
  border-radius: 8px;
  font-size: 13px;
}

.error-text {
  color: #dc2626;
  margin: 0;
}

.packages-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  gap: 0.6rem;
}

.package-cost-selector.selector-inline .packages-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 0.6rem;
  grid-template-columns: unset;
}

.package-item {
  display: block;
}

.package-cost-selector.selector-inline .package-item {
  flex-shrink: 0;
  width: auto;
}

.package-radio {
  display: block;
  cursor: pointer;
}

.radio-input {
  display: none;
}

.package-card {
  border: 2px solid #e2e8f0;
  border-radius: 12px;
  padding: 0.6rem 0.7rem;
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
  box-shadow: 0 2px 8px -2px rgba(15, 23, 42, 0.08), 0 1px 3px -1px rgba(15, 23, 42, 0.04);
  min-height: auto;
  display: flex;
  flex-direction: column;
  gap: 0.4rem;
  position: relative;
}

.package-cost-selector.selector-inline .package-card {
  border-radius: 10px;
  padding: 0.55rem 0.85rem;
  gap: 0.3rem;
  min-width: auto;
  max-width: none;
  width: auto;
  justify-content: flex-start;
  align-items: center;
  flex-direction: row;
  background: linear-gradient(135deg, #ffffff 0%, #fafbfc 100%);
  border: 1.5px solid #dbe4ed;
}

.radio-input:checked + .package-card {
  border-color: #10b981;
  background: linear-gradient(135deg, #ecfdf5 0%, #dffcf0 100%);
  box-shadow: 0 4px 14px -2px rgba(16, 185, 129, 0.35), 0 2px 6px -1px rgba(16, 185, 129, 0.15);
  transform: translateY(-2px);
}

.package-card.is-selected {
  border-color: #10b981;
  background: linear-gradient(135deg, #ecfdf5 0%, #dffcf0 100%);
  box-shadow: 0 4px 14px -2px rgba(16, 185, 129, 0.35), 0 2px 6px -1px rgba(16, 185, 129, 0.15);
  transform: translateY(-2px);
}

.package-cost-selector.selector-inline .radio-input:checked + .package-card {
  border-color: #10b981;
  background: linear-gradient(135deg, #ecfdf5 0%, #f0fdf4 100%);
  box-shadow: 0 4px 12px -2px rgba(16, 185, 129, 0.4), 0 2px 4px -1px rgba(16, 185, 129, 0.2);
  transform: translateY(0);
}

.package-cost-selector.selector-inline .package-card.is-selected {
  border-color: #10b981;
  background: linear-gradient(135deg, #ecfdf5 0%, #f0fdf4 100%);
  box-shadow: 0 4px 12px -2px rgba(16, 185, 129, 0.4), 0 2px 4px -1px rgba(16, 185, 129, 0.2);
  transform: translateY(0);
}

.package-cost-selector.selector-inline .radio-input:checked + .package-card .package-name {
  color: #047857;
  font-weight: 800;
}

.package-cost-selector.selector-inline .package-card.is-selected .package-name {
  color: #047857;
  font-weight: 800;
}

.package-cost-selector.selector-inline .radio-input:checked + .package-card .unit-cost {
  color: #047857;
  font-weight: 800;
}

.package-cost-selector.selector-inline .package-card.is-selected .unit-cost {
  color: #047857;
  font-weight: 800;
}

.package-card:hover {
  border-color: #cbd5e1;
  box-shadow: 0 4px 14px -2px rgba(15, 23, 42, 0.15), 0 2px 6px -1px rgba(15, 23, 42, 0.08);
  transform: translateY(-1px);
}

.card-main {
  display: flex;
  flex-direction: column;
  gap: 0.4rem;
  flex: 1;
}

.package-cost-selector.selector-inline .card-main {
  display: flex;
  flex-direction: row;
  gap: 0;
  flex: 1;
}

.card-top {
  display: flex;
  align-items: flex-start;
  gap: 0.5rem;
  justify-content: space-between;
}

.card-top {
  display: flex;
  align-items: flex-start;
  gap: 0.5rem;
  justify-content: space-between;
}

.package-cost-selector.selector-inline .card-top {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  gap: 0.8rem;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 0.5rem;
  margin-bottom: 0.4rem;
}

.package-cost-selector.selector-inline .card-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  gap: 0.6rem;
  margin: 0;
  width: 100%;
}

.package-name {
  font-size: 12px;
  font-weight: 600;
  color: #0f172a;
  flex: 1;
  word-break: break-word;
  line-height: 1.3;
}

.package-cost-selector.selector-inline .package-name {
  font-size: 13px;
  font-weight: 700;
  color: #1e293b;
  text-align: left;
  white-space: normal;
  overflow: visible;
  text-overflow: unset;
  max-width: none;
  line-height: 1.3;
  flex: 1;
  margin: 0;
  letter-spacing: 0.02em;
}

.package-code {
  font-size: 10px;
  font-weight: 600;
  color: #64748b;
  background: #f1f5f9;
  padding: 0.15rem 0.35rem;
  border-radius: 3px;
  white-space: nowrap;
  flex-shrink: 0;
}

.package-cost-selector.selector-inline .package-code {
  display: none;
}

.card-info {
  display: flex;
  align-items: baseline;
  gap: 0.2rem;
  margin-bottom: 0.3rem;
}

.package-cost-selector.selector-inline .card-info {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 0.3rem;
  margin: 0;
  flex-shrink: 0;
  white-space: nowrap;
  padding-left: 0.8rem;
  border-left: 1px solid #e5e7eb;
}

.card-desc {
  font-size: 11px;
  color: #64748b;
  line-height: 1.3;
  word-break: break-word;
  max-height: 1.95em;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  line-clamp: 2;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.package-cost-selector.selector-inline .card-desc {
  display: none;
}

.unit-cost {
  font-size: 12px;
  font-weight: 700;
  color: #059669;
}

.package-cost-selector.selector-inline .unit-cost {
  font-size: 14px;
  font-weight: 700;
  color: #10b981;
  letter-spacing: 0.01em;
}

.empty-state,
.no-match-state {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 1.5rem;
  color: #64748b;
  font-size: 14px;
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
}

.empty-state p,
.no-match-state p {
  margin: 0;
}


.view-bom-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  padding: 0;
  font-size: 11px;
  font-weight: 600;
  color: #1e40af;
  background: linear-gradient(135deg, #dbeafe, #e0e7ff);
  border: 1px solid #93c5fd;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.18s;
  flex-shrink: 0;
}

.package-cost-selector.selector-inline .view-bom-btn {
  display: none;
}

.view-bom-btn:hover {
  background: linear-gradient(135deg, #93c5fd, #c7d2fe);
  box-shadow: 0 2px 6px -2px rgba(30, 64, 175, 0.3);
  transform: translateY(-1px);
}

.view-bom-btn:active {
  transform: translateY(0);
}

.view-bom-btn svg {
  width: 16px;
  height: 16px;
  stroke-width: 2;
}
</style>
